const MongoClient = require('mongodb').MongoClient

const url = 'mongodb://localhost:27017'
const dbName = 'myblogs'

MongoClient.connect(
	url,
	{
		// 配置
		useUnifiedTopology: true
	},
	(err, client) => {
		if (err) {
			console.error('mongodb connect error', err)
			return
		}

		// 没有报错，说明连接成功
		console.log('mongodb connect success')

		// 切换到数据库（控制台 `use myblog`）
		const db = client.db(dbName)

		const usersCollection = db.collection('users')

		//
		usersCollection.insertOne(
			{
				username: 'devin',
				password: '123',
				realname: 'devinwang'
			},
			(err, result) => {
				console.log('result:', result)
			},
			(err, res) => {
				console.log('ere', res)
			}
		)

		usersCollection.updateOne(
			{
				name: 'test'
			},
			{ $set: { username: 'testname' } }
		)

		usersCollection.find().toArray((err, result) => {
			// console.log('result:', result)
			// // 关闭连接
			// client.close()
		})
	}
)
